// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.units

import android.content.Context
import xyz.apiote.bimba.czwek.R
import java.text.NumberFormat

object Imperial : UnitSystem(10) {
	override fun timeUnit(count: Long): TimeUnit = Second(count.toDouble())
	override fun timeUnit(other: TimeUnit): TimeUnit = Second(other)

	override fun speedUnit(count: Double): SpeedUnit = Miph(count)
	override fun speedUnit(other: SpeedUnit): SpeedUnit = Miph(other)

	override fun distanceUnit(count: Double): DistanceUnit = MiYd(count)
	override fun distanceUnit(other: DistanceUnit): DistanceUnit = MiYd(other)

	override fun toString(context: Context, s: SpeedUnit): String = s.toString(context, base)
	override fun toString(context: Context, t: TimeUnit): String = t.toString(context, base)
	override fun toString(context: Context, d: DistanceUnit): String = d.toString(context, base)
}

class Miph(val miph: Double) : SpeedUnit {
	constructor(s: Int) : this(s.toDouble())
	constructor(other: SpeedUnit) : this(other.mps() / 0.44704)

	override fun mps(): Double = miph * 0.44704
	override fun toString(context: Context, base: Int): String =
		context.getString(
			R.string.speed_in_mi_per_h,
			NumberFormat.getInstance().apply { maximumFractionDigits = 2 }.format(miph)
		)

	override fun contentDescription(context: Context, base: Int): String =
		context.resources.getQuantityString(
			R.plurals.speed_in_mi_per_h_cd, miph.toInt(), miph.toInt()
		)
}

class MiYd(val mi: Double) : DistanceUnit {
	constructor(other: DistanceUnit) : this(other.meters() / 1609.344)

	override fun meters(): Double = mi * 1609.344

	override fun toString(context: Context, base: Int): String =
		if (mi < 1) {
			context.getString(
				R.string.distance_in_yd,
				NumberFormat.getIntegerInstance().format((mi * 1760).toInt())
			)
		} else {
			context.getString(
				R.string.distance_in_mi,
				NumberFormat.getInstance().apply { maximumFractionDigits = 2 }.format(mi)
			)
		}

	override fun contentDescription(context: Context, base: Int): String =
		if (mi < 1) {
			context.resources.getQuantityString(
				R.plurals.distance_in_yd_cd,
				(mi / 1760).toInt(),
				(mi / 1760).toInt()
			)
		} else {
			val miles = mi.toInt()
			val yards = ((mi - miles) * 1760).toInt()
			val miString = context.resources.getQuantityString(R.plurals.distance_in_mi_cd, miles)
			val ydString = context.resources.getQuantityString(R.plurals.distance_in_yd_cd, yards)
			if (yards > 0) {
				context.getString(R.string.distance_in_two_units_cd, miString, ydString)
			} else {
				miString
			}
		}
}